package com.foxnicweb.app.patent.job;

import com.alibaba.fastjson.JSONObject;
import com.github.foxnic.api.transter.Result;
import com.github.foxnic.commons.cache.Variable;
import com.github.foxnic.commons.collection.MapUtil;
import com.github.foxnic.commons.lang.StringUtil;
import com.github.foxnic.commons.log.Logger;
import com.github.foxnic.commons.network.HttpClient;
import org.github.foxnic.web.domain.job.JobExecutor;
import org.github.foxnic.web.domain.system.Tenant;
import org.github.foxnic.web.proxy.system.TenantServiceProxy;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

public  abstract   class BaseJobExecutor implements JobExecutor {

    public static String CALLER_ACCOUNT="admin";

    @Value("${patent.tenant-id}")
    protected String tenantId;

    protected String companyId = null;

    public static final String CHARSET = "UTF-8";
    private Variable token=new Variable(null,1000 * 60 * 60 * 5);

    @Value("${patent.api-url}")
    private String baseApiUrl=null;

    @Value("${patent.username}")
    private String username=null;

    @Value("${patent.password}")
    private String password=null;

    private HttpClient client=new HttpClient();

    protected void initIf() {
        if(this.companyId!=null) return;


        Result<Tenant> tenantResult =  TenantServiceProxy.api().getById(tenantId);
        if(tenantResult.failure()){
            throw new IllegalArgumentException("租户ID错误");
        }
        this.companyId=tenantResult.data().getCompanyId();
        if(StringUtil.isBlank(this.companyId)){
            throw new IllegalArgumentException("租户未指定公司");
        }
    }

    protected void refreshToken() {
        String url= StringUtil.joinUrl(baseApiUrl,"/login");
        try {
            String json = client.post(url,MapUtil.asMap("username",this.username,"password",this.password), CHARSET);
            JSONObject result=JSONObject.parseObject(json);
            if(result.getInteger("status")==1) {
                JSONObject data=result.getJSONObject("data");
                String token=data.getString("token");
                this.token.setValue(token);
            }
        } catch (Exception e){
            Logger.exception(e);
        }
    }

    protected JSONObject post(String api, Map<String, String> params) {
        String url= StringUtil.joinUrl(baseApiUrl,api);
        Map<String, String> headers=new HashMap<>();
        String tokenValue= token.stringValue();
        if(StringUtil.isBlank(tokenValue)) {
            refreshToken();
            tokenValue= token.stringValue();
        }
        headers.put("token",tokenValue);
        try {
            String json = client.post(url,params,headers,CHARSET);
            System.out.println();
        } catch (Exception e){
            Logger.exception(e);
        }
        return null;
    }

    protected JSONObject get(String api, Map<String, String> params,String dataKey) {
        String url= StringUtil.joinUrl(baseApiUrl,api);
        Map<String, String> headers=new HashMap<>();
        String tokenValue= token.stringValue();
        if(StringUtil.isBlank(tokenValue)) {
            refreshToken();
            tokenValue= token.stringValue();
        }
        headers.put("token",tokenValue);
        try {
            String json = client.get(url,params,headers,CHARSET);
            JSONObject result = JSONObject.parseObject(json);
            Integer status=result.getInteger("status");
            if(status!=null && status==1) {
                return result.getJSONObject(dataKey);
            } else {
                return null;
            }
        } catch (Exception e) {
            Logger.exception(e);
            return null;
        }
    }
}
